package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.exception.code.UserStatusCode;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.user.common.AppJwtUtil;
import com.usian.user.common.BCrypt;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    /**
     * 自媒体用户登录功能实现
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDto dto) {
        //检查参数
        if (StringUtils.isEmpty(dto.getName())|| StringUtils.isEmpty(dto.getPassword())){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"用户名密码不能为空");
        }
        //根据用户名获取用户信息  失败提示用户
        WmUser wmUser=this.getOne(new LambdaQueryWrapper<WmUser>().eq(WmUser::getName,dto.getName()));
        if (wmUser==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"该用户不存在");
        }
        //获取用户信息成功  判断密码  失败提示信息
    if (!BCrypt.checkpw(dto.getPassword(),wmUser.getPassword())){
        CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"用户密码有误");
        }
        //登陆成功  签发token
        String token=AppJwtUtil.getToken(Long.parseLong(wmUser.getId()+""));
       //返回jwt数据
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        wmUser.setPassword("");
        wmUser.setSalt("");
        map.put("user",wmUser);
        return ResponseResult.okResult(map);




    }
}
